import {
  config
} from '../config.js'

class HTTP {
  constructor() {
    this.baseUrl = config.api_url
  }

  request(params) {
    let url = this.baseUrl + params.url;

    if (!params.method) {
      params.method = 'GET';
    }
    if (!params.data) {
      params.data = {};
    }
    if (!params.header) {
      params.header = {
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }

    wx.request({
      url: url,
      data: params.data,
      method: params.method,
      header: params.header,
      success: (res) => {
        const code = res.statusCode.toString();
        if (code.startsWith("2")) {
          const data = res.data
          params.success && params.success(res.data)
        } else {
          params.fail && params.fail(res)
        }
      },
      fail: (err) => {
        params.fail && params.fail(err)
      },
      complete: (res) => {
        params.complete && params.complete(res)
      }
    })
  }

  promise({url, data={}, method = "GET", header}) {
    url = this.baseUrl + url
    if (!header) {
      header = {
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }

    return new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        data: data,
        method: method,
        header: header,
        success: (res) => {
          const code = res.statusCode.toString();
          if (code.startsWith("2")) {
            const data = res.data 
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }
}

export {
  HTTP
}